package ynu.sxp.demoapp.cart.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.modelmapper.ModelMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.sxp.demoapp.cart.dto.CartProductRO;
import ynu.sxp.demoapp.cart.dto.CartRO;
import ynu.sxp.demoapp.cart.entity.CartEntity;
import ynu.sxp.demoapp.cart.service.CartService;
import ynu.sxp.demoapp.cart.util.CartProductMapper;
import ynu.sxp.demoapp.user.dto.UserVO;
import ynu.sxp.demoapp.user.entity.UserEntity;
import ynu.sxp.demoapp.user.service.UserService;

import java.util.UUID;

@RestController
@Tag(name = "Cart", description = "购物车" )
@RequestMapping("/api/cart")
public class CartController {
    private final CartService cartService;
    private final UserService userService;
    private final ModelMapper modelMapper;
    private final CartProductMapper cartProductMapper;

    public CartController(CartService cartService, UserService userService, ModelMapper modelMapper, CartProductMapper cartProductMapper) {
        this.cartService = cartService;
        this.userService = userService;
        this.modelMapper = modelMapper;
        this.cartProductMapper = cartProductMapper;
    }

    @GetMapping("add")
    @Operation(summary = "添加商品", description = "向购物车添加商品")
    public ResponseEntity<CartRO> addProduct(@RequestBody CartProductRO cartProductRO) {
        System.out.println("Received CartProductRO: " + cartProductRO);
        UUID userId = cartService.getCartById(cartProductRO.getCartId()).getUser().getId();
        UUID productId = cartProductRO.getProduct().getId();
        int quantity = cartProductRO.getQuantity();
        CartEntity cart = cartService.addProductToCart(userId, productId, quantity);
        CartRO cartRO = new CartRO();
        cartRO.setUser(modelMapper.map(userService.getUserById(userId), UserVO.class));
        cartRO.setCartProducts(cartProductMapper.toCartProductROList(cart.getCartProducts()));
        return ResponseEntity.status(HttpStatus.CREATED).body(cartRO);
    }

    @GetMapping("info")
    @Operation(summary = "获取购物车信息", description = "获取购物车商品列表")
    public CartEntity getCart(@RequestParam("id") UUID userid) {
        return cartService.getCartByUser(userid);
    }

    @PostMapping("create")
    @Operation(summary = "创建购物车", description = "为已有用户创建一个新的购物车")
    public ResponseEntity<CartEntity> createCart(@RequestParam("id") UUID userId) {
        CartEntity cart = cartService.createCart(userId);
        return ResponseEntity.status(HttpStatus.CREATED).body(cart);
    }

}
